/**
 * Copyright (C) 2010 DustedPixels.com
 */
package com.dustedpixels.cirt.model.video;

import com.dustedpixels.cirt.model.core.Circuit;
import com.dustedpixels.cirt.model.core.In;
import com.dustedpixels.cirt.model.core.Pins;
import com.dustedpixels.cirt.model.core.Script;

/**
 * Video
 *
 * @author Michal Pociecha-Los (micapolos@gmail.com)
 */
@Circuit
public final class ByteVideo {
  @In public boolean blank;
  @In public boolean hSync;
  @In public boolean vSync;
  @In @Pins(8) public int color;
  
  private final byte[] byteArray;
  private final int width;
  private final int height;
  private final int scanlineStride;
  
  private int x;
  private int y;
  private int lineCounter;
  
  public ByteVideo(byte[] byteArray, int width, int height, int scanlineStride) {
    this.byteArray = byteArray;
    this.width = width;
    this.height = height;
    this.scanlineStride = scanlineStride;
  }
  
  @Script
  public void update() {
    if (!blank) {
      if (x < width && y < height) {
        //System.out.println("Outputting: " + x + "-" + y + "=" + color);
        byteArray[y * width + x] = (byte) color;
      }
      
      x++;
    }
    
    if (hSync) {
      x = 0;
    }
    
    if (vSync) {
      y = 0;
      lineCounter = 0;
    } else {
      lineCounter++;
      if (lineCounter == scanlineStride) {
        lineCounter = 0;
        y++;
      }
    }
  }
}
